# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import os, urllib2, time
from deal_info_api import *

def deal_info_time(f_xml, subdeal, li_from, li_to, tabsum):
    subdeal_li = subdeal.getiterator(li_from)

    ut = time.gmtime(int(subdeal_li[0].text) + 28800)

    t = '%Y-%m-%d %X'

    f_xml.write(('\t' * tabsum + '<%s>%s+0800</%s>\n' % (li_to, time.strftime(t, ut), li_to)).encode('utf-8'))

def deal_city(city_node, city):
    f_xml = open('%sxml/kutuan_%s.xml' % (get_home_dir(), city), 'a')

    deal = city_node

    f_xml.write('\t' + '<deal>\n')
    deal_info_source(f_xml, 'kutuan', '酷团'.decode('utf-8'), 'http://www.kutuan.com/', 'http://www.kutuan.com/')
    f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

    deal_info_add(f_xml, deal, 'url', 'id', 2)
    deal_info_add(f_xml, deal, 'title', 'name', 2)
    deal_info_cats(f_xml, deal, 'title')
    deal_info_vendor_2(f_xml)
    deal_info_time(f_xml, deal, 'beginTime', 'start_time', 2)
    deal_info_time(f_xml, deal, 'endTime', 'end_time', 2)
    deal_info_add(f_xml, deal, 'primaryPrice', 'o_price', 2)
    deal_info_add(f_xml, deal, 'price', 'c_price', 2)
    deal_info_discount_and_save_money(f_xml, deal, 'price', 'primaryPrice')
    deal_info_img(f_xml, deal, 'image')
    deal_info_add(f_xml, deal, 'url', 'url', 2)

    f_xml.write('\t' + '</deal>\n')



os.system('ls %sxml/kutuan_*.xml > %slist/kutuan_xml_list' % (get_home_dir(), get_home_dir()))
xml_list = open('%slist/kutuan_xml_list' % (get_home_dir()), 'r')
while 1 + 1 == 2:
    xml_file = xml_list.readline().replace('\n', '')
    if len(xml_file):
	os.system('mv %s%s %s%s.orig' % (get_home_dir(), xml_file, get_home_dir(), xml_file))
    else:
	break
xml_list.close()
os.system('rm %slist/kutuan_xml_list' % (get_home_dir()))

f_city_list = open('%slist/citylist' % (get_home_dir()), 'r')
city_list = eval(f_city_list.read())

f_url = urllib2.urlopen('http://www.kutuan.com/tuangou/api')

root_url = ET.fromstring(f_url.read())

cities = [0] * 1000
city_sum = 0
exist = '|'

root = root_url.getiterator('tuangou')
for node in root:
    city_name = node.getiterator('city')
    try:
    	deal_city(node, city_list[city_name[0].text.encode('utf-8')])
	if exist.find(city_list[city_name[0].text.encode('utf-8')]) == -1:
		cities[city_sum] = city_list[city_name[0].text.encode('utf-8')]
		exist += city_list[city_name[0].text.encode('utf-8')] + '|'
		city_sum += 1
    except KeyError:
	os.system(('date >> %serror.log && echo "%s KeyError: %s\n" >> %serror.log' % (get_home_dir(), 'kutuan', city_name[0].text)).encode('utf-8'), get_home_dir())

for i in range(city_sum):
    os.system('mv %sxml/kutuan_%s.xml %sxml/kutuan_%s.xml.bak' % (get_home_dir(), cities[i], get_home_dir(), cities[i]))
    f_tmp = open('%sxml/kutuan_%s.xml' % (get_home_dir(), cities[i]), 'w')
    f_bak = open('%sxml/kutuan_%s.xml.bak' % (get_home_dir(), cities[i]), 'r')
    f_tmp.write('<deals>\n')
    f_tmp.write(f_bak.read())
    f_tmp.write('</deals>\n')
    f_tmp.close()
    f_bak.close()
    os.system('rm %sxml/kutuan_%s.xml.bak' % (get_home_dir(), cities[i]))

    tuan = 'kutuan'
    city = cities[i]
    os.system('cp %sxml/%s_%s.xml %sxml/%s_%s.xml.bak' % (get_home_dir(), tuan, city, get_home_dir(), tuan, city))
    f_bak = open('%sxml/%s_%s.xml.bak' % (get_home_dir(), tuan, city), 'r')
    bak = f_bak.read()
    f_bak.close()

    if not os.path.isfile('%sxml/%s_%s.xml.orig' % (get_home_dir(), tuan, city)):
	os.system('echo "<deals>\n</deals>" > %sxml/%s_%s.xml.orig' % (get_home_dir(), tuan, city))
    f_orig = open('%sxml/%s_%s.xml.orig' % (get_home_dir(), tuan, city), 'r')
    orig = f_orig.read()
    f_orig.close()

    if not os.path.isfile('%slist/%s_%s_id' % (get_home_dir(), tuan, city)):
	os.system('touch %slist/%s_%s_id' % (get_home_dir(), tuan, city))
    global f_id
    f_id = open('%slist/%s_%s_id' % (get_home_dir(), tuan, city), 'r+a')
    global d_id
    d_id = f_id.read()

    root = ET.fromstring(bak)

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = root.getiterator('deal')

    for deal in deals:
	if judge(f_id, d_id, deal, 'id'):
	    continue
	f_xml.write('\t' + '<deal>\n')
	for x in deal:
	    if x.tag == 'source' or x.tag == 'vendor':
		f_xml.write('\t' * 2 + '<%s>\n' % (x.tag))
		for y in x:
		    f_xml.write(('\t' * 3 +'<%s>%s</%s>\n' % (y.tag, y.text, y.tag)).encode('utf-8'))
		f_xml.write('\t' * 2 + '</%s>\n' % (x.tag))
	    else:
		f_xml.write(('\t' * 2 +'<%s>%s</%s>\n' % (x.tag, x.text, x.tag)).encode('utf-8'))
	f_xml.write('\t' + '</deal>\n')


    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'r')
    d_xml = f_xml.read()
    f_xml.close()
    if d_xml.find('<deals>\n</deals>') > -1:
	os.system('rm %sxml/%s_%s.xml' % (get_home_dir(), tuan, city))
    os.system('rm %sxml/%s_%s.xml.orig' % (get_home_dir(), tuan, city))
    os.system('rm %sxml/%s_%s.xml.bak' % (get_home_dir(), tuan, city))

	        

